package com.mz.mattress.client.service.impl;

import com.mz.mattress.api.common.Result;
import com.mz.mattress.api.entity.CouponSendRecord;
import com.mz.mattress.api.util.DateUtil;
import com.mz.mattress.api.util.StringTools;
import com.mz.mattress.client.mapper.CouponSendRecordMapper;
import com.mz.mattress.client.service.CouponSendRecordService;
import com.mz.mattress.client.service.CouponService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class CouponSendRecordServiceImpl implements CouponSendRecordService {

    @Autowired
    private CouponSendRecordMapper couponSendRecordMapper;

    @Autowired
    private CouponService couponService;

    @Override
    public Result sendById(Integer id) {

        CouponSendRecord record = couponSendRecordMapper.selectById(id);
        if (record == null) {
            return Result.fail("找不到记录");
        }

        if (record.getStatus() == 2) {
            return Result.fail("已发放过");
        }

        return sendByRecord(record);
    }

    private Result sendByRecord(CouponSendRecord record) {

        Result result = couponService.sendCouponByMobile(record.getMobile(), record.getCouponId(), record.getCount());

        CouponSendRecord update = new CouponSendRecord();
        update.setId(record.getId());
        update.setStatus(result.isSuccess() ? 2 : 1);
        update.setSendTime(DateUtil.getNowDateTime());
        couponSendRecordMapper.updateById(update);

        return Result.ok();
    }

    @Override
    public Result loadByMobile(String mobile) {

        if (StringTools.isEmpty(mobile)) {
            return Result.fail();
        }

        List<CouponSendRecord> list = couponSendRecordMapper.selectByMobile(mobile);

        for (CouponSendRecord record : list) {
            sendByRecord(record);
        }

        return Result.ok();
    }
}
